import { test } from '@playwright/test';
import fs from 'fs';
import path from 'path';

const LOG_DIR = path.resolve(__dirname, '../debug_logs');
const NETWORK_LOG = path.join(LOG_DIR, 'huawei_live_network.log');
const CONSOLE_LOG = path.join(LOG_DIR, 'huawei_live_console.log');
const SUMMARY_LOG = path.join(LOG_DIR, 'huawei_live_summary.json');

function ensureLogDir() {
  if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true });
}

function appendLog(file: string, line: string) {
  fs.appendFileSync(file, `${new Date().toISOString()} ${line}\n`);
}

function writeJson(file: string, data: any) {
  fs.writeFileSync(file, JSON.stringify(data, null, 2));
}

// Filters for Vhall dispatch endpoints
const DISPATCH_PATTERNS = [
  /gslb\.e\.vhall\.com\/api\/dispatch_replay/i,
  /vhallyun\.com\/api\/dispatch_replay/i,
];

// Normalize URL for deduping
function baseUrl(url: string) {
  try {
    const u = new URL(url);
    u.search = '';
    return u.toString();
  } catch {
    return url;
  }
}

/**
 * Test: Navigate to Huawei live page, capture network and console, and summarize dispatch_replay behavior
 */
 test.describe('Huawei Live Page Network Diagnostics', () => {
  test('Capture network requests and identify repeated dispatch_replay calls', async ({ page }) => {
    ensureLogDir();

    // Capture console logs
    page.on('console', msg => {
      appendLog(CONSOLE_LOG, `[${msg.type()}] ${msg.text()}`);
    });

    // Capture network requests
    const dispatchRequests: Array<{ url: string; method: string; status?: number; tabulatedUrl: string }>[] = [] as any;
    const seen = new Map<string, number>(); // baseUrl -> count

    page.on('request', req => {
      const url = req.url();
      const method = req.method();
      if (DISPATCH_PATTERNS.some(p => p.test(url))) {
        const tabulated = baseUrl(url);
        appendLog(NETWORK_LOG, `[REQUEST] ${method} ${url}`);
        seen.set(tabulated, (seen.get(tabulated) || 0) + 1);
      }
    });

    page.on('response', async res => {
      const url = res.url();
      if (DISPATCH_PATTERNS.some(p => p.test(url))) {
        const status = res.status();
        appendLog(NETWORK_LOG, `[RESPONSE] ${status} ${url}`);
        try {
          const text = await res.text();
          // Avoid logging huge payloads, but note if token present
          const hasToken = /\"token\"\s*:\s*\"/.test(text);
          appendLog(NETWORK_LOG, `[BODY] hasToken=${hasToken} length=${text.length}`);
        } catch (e) {
          appendLog(NETWORK_LOG, `[BODY] error reading body: ${(e as Error).message}`);
        }
      }
    });

    // Navigate to Huawei live page
    const target = 'https://bbs.huaweicloud.com/live/cloud_live/202510211700.html';
    await page.goto(target, { waitUntil: 'domcontentloaded' });

    // Observe for a fixed time window to collect repeated behavior
    await page.waitForTimeout(15000); // 15 seconds collection window

    // Summarize
    const summary = Array.from(seen.entries()).map(([u, cnt]) => ({ url: u, count: cnt }));
    writeJson(SUMMARY_LOG, {
      page: target,
      timestamp: new Date().toISOString(),
      dispatchSummary: summary,
    });
  });
});